#!/usr/bin/bash
# This is the one-liner installation script for these dotfiles. To install,
# run one of these two commands:
#
#     $ wget -qO- "gitee.com/liuyvjin/custom-ohmyzsh/raw/master/my_scripts/win_updatezsh.sh" | bash
# or
#     $ curl -sL "gitee.com/liuyvjin/custom-ohmyzsh/raw/master/my_scripts/win_updatezsh.sh" | bash
#
# Author: liujin


ZSH="$HOME/.oh-my-zsh"
ONCE_FLAG=$([[ -d $ZSH ]]; echo $?)  # 初次安装为 1
# SCRIPT_PATH="$( cd -- "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )"

# 设置输出颜色
setup_color() {
	# Only use colors if connected to a terminal
	if [ -t 1 ]; then
		RED=$(printf '\033[31m')
		GREEN=$(printf '\033[32m')
		YELLOW=$(printf '\033[33m')
		BLUE=$(printf '\033[34m')
		BOLD=$(printf '\033[1m')
		RESET=$(printf '\033[m')
	else
		RED=""
		GREEN=""
		YELLOW=""
		BLUE=""
		BOLD=""
		RESET=""
	fi
}
setup_color

# 初次安装一些工具
install_tools_once() {
    echo "${GREEN}>>> Install useful tools.${RESET}"
    pacman -Syu
    pacman -S vim man tmux openssh zsh nnn git
}

# 初次安装 ohmyzsh
install_ohmyzsh_once() {
    echo "${GREEN}>>> Install oh-my-zsh${RESET}"
    bash -c "$(wget -qO- "gitee.com/liuyvjin/custom-ohmyzsh/raw/master/tools/install.sh")  --unattended"
}

# 更新配置文件
setup_dotfiles(){
    echo "${GREEN}>>> Copy dotfiles${RESET}"
    # copy dotfiles
    cp -i -v "$ZSH"/dotfiles/.condarc "$HOME"/.condarc
    cp -i -v "$ZSH"/dotfiles/.vimrc "$HOME"/.vimrc
    cp -i -v "$ZSH"/dotfiles/.gitmessage "$HOME"/.gitmessage
    cp -i -v "$ZSH"/dotfiles/win/.[^.]* "$HOME"/   # .minttyrc, .tmux.conf
    cp -i -v "$ZSH"/dotfiles/.zshrc "$HOME"/.zshrc  # .zshrc

    # vim color themes
    if [[ ! -d "$HOME"/.vim/colors ]]; then
        mkdir -p "$HOME"/.vim/colors
    fi
    cp -n -v "$ZSH"/dotfiles/vim_colors/* "$HOME"/.vim/colors  # do not overwrite

    # ssh 客户端配置文件模板
    if [[ ! -d "$HOME"/.ssh ]]; then
        mkdir -p "$HOME"/.ssh
    fi
    cp -n -v "$ZSH"/dotfiles/ssh/* "$HOME"/.ssh/  # do not overwrite

    # 启用 git message template
    git config --global commit.template "$HOME"/.gitmessage
}

# main
if (( ONCE_FLAG > 0 ))     # 执行初次安装的配置
then
    install_tools_once
    install_ohmyzsh_once
else                        # 非初次安装更新仓库
    echo "${GREEN}>>> Updating oh-my-zsh${RESET}"
    cur_path=$(pwd)
    cd $ZSH
    git pull origin master
    cd $cur_path
fi

setup_dotfiles

# 解决 ERROR: this script is obsolete, please see git-completion.zsh
mkdir -p ~/.config/git/
touch ~/.config/git/git-prompt.sh

echo "${YELLOW}>>> Please log out and log back in.${RESET}"
